package com.hq.lgx


import java.io.IOException
import java.net.*
import java.util.*


class LanGame{
    var multicastSocket = MulticastSocket(9966)
    val group = InetAddress.getByName("224.0.0.244")
    fun init(){
        multicastSocket.joinGroup(group)
        //多播true表示不接受本机发送数据
        multicastSocket.loopbackMode=true
    }
    fun sayHelloToAll(positons:String){
        try {
            var buf = positons.toByteArray()
            val packet = DatagramPacket(buf, buf.size, group, 9966)

            multicastSocket.send(packet)
        } catch (e: InterruptedException) {
        } catch (e: IOException) {
            e.printStackTrace()
            multicastSocket.close()
        }
    }

    fun localIp():String{
        val en: Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()
        while (en.hasMoreElements()) {
            val intf: NetworkInterface = en.nextElement()
            val enumIpAddr: Enumeration<InetAddress> = intf.inetAddresses
            while (enumIpAddr.hasMoreElements()) {
                val inetAddress: InetAddress = enumIpAddr.nextElement()
                if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                    return inetAddress.hostAddress.toString()
                }
            }
        }
        return "null"
    }
    fun receive():String{
        var arb = ByteArray(1024)
        var datagramPacket = DatagramPacket(
            arb,
            arb.lastIndex+1
        )
        multicastSocket.receive(datagramPacket)
        var content  = String(arb)

        return content;
    }

}
//fun main(args: Array<String>) {
//    var lanGame = LanGame()
//    var lanGam1e = LanGame()
//    lanGame.init()
// Thread{
//     while (true){
//         lanGame.sayHelloToAll("xxx")
//     }
// }.start()
//    while (true){
//        val receive = lanGame.receive()
//        print(receive)
//    }
//
//
//}

